package com.hua.yuan.ui;

import android.Manifest;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hua.yuan.R;
import com.hua.yuan.base.BaseAppActivity;
import com.hua.yuan.ui.adapter.ImageCommonAdapter;
import com.hua.yuan.ui.data.PictureDataRequest;
import com.hua.yuan.ui.module.ImageDetail;
import com.hua.yuan.ui.module.ImageDetailCommonBean;
import com.hua.yuan.util.JsonUtil;
import com.hua.yuan.util.ToastUtil;
import com.hua.yuan.util.loadimage.DownImageUtil;
import com.hua.yuan.util.loadimage.ImageCallBack;
import com.hua.yuan.util.loadimage.XPermissionUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 时间：2018/9/2
 * 作者：蓝天
 * 描述：
 */
public class ImageBigActivity extends BaseAppActivity implements ViewPager.OnPageChangeListener {
    ImageView backImage;
    TextView titleView;

    ViewPager vp_viewpager;

    LinearLayout ll_bottom_simple;
    TextView tv_pagenum_simple;
    EditText sendEt_simple;
    TextView videoDisSendTv_simple;
    LinearLayout buttonDownLl_simple;
    TextView tv_more_comment_simple;


    LinearLayout ll_bottom;
    ImageView iv_comment_close;
    ListView lv_comment;
    EditText sendEt;
    TextView videoDisSendTv;

    ImageDetail imageDetail;
    int position;
    DownImageUtil mDownImageUtil;
    int loadCount = 0;


    @Override
    protected int initLayoutId() {
        return R.layout.activity_imagebig;
    }

    @Override
    protected void initView() {

        backImage = findViewById(R.id.backImage);
        titleView = findViewById(R.id.titleView);

        vp_viewpager = findViewById(R.id.vp_viewpager);
        vp_viewpager.setOnPageChangeListener(this);

        ll_bottom_simple = findViewById(R.id.ll_bottom_simple);
        tv_pagenum_simple = findViewById(R.id.tv_pagenum_simple);
        sendEt_simple = findViewById(R.id.sendEt_simple);
        videoDisSendTv_simple = findViewById(R.id.videoDisSendTv_simple);
        buttonDownLl_simple = findViewById(R.id.buttonDownLl_simple);
        tv_more_comment_simple = findViewById(R.id.tv_more_comment_simple);

        ll_bottom = findViewById(R.id.ll_bottom);
        iv_comment_close = findViewById(R.id.iv_comment_close);
        lv_comment = findViewById(R.id.lv_comment);
        sendEt = findViewById(R.id.sendEt);
        videoDisSendTv = findViewById(R.id.videoDisSendTv);

        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mDownImageUtil = new DownImageUtil(ImageBigActivity.this);
        buttonDownLl_simple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //权限管理
                XPermissionUtils.requestPermissions(ImageBigActivity.this, 1, new String[]{Manifest.permission
                        .READ_EXTERNAL_STORAGE, Manifest.permission
                        .WRITE_EXTERNAL_STORAGE}, new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        //第一个参数为下载地址，第二个参数为图片名，第三个参数为目录名
                        //  地址为格式：/storage/emulated/0/cwj/img/Test/1.png
                        mDownImageUtil.onDownLoad(
                                imageDetail.getPictures_list().get(loadCount).getImg_url(),
                                (int) System.currentTimeMillis(),
                                "tuji");
                    }

                    @Override
                    public void onPermissionDenied() {
                        Toast.makeText(ImageBigActivity.this, "请打开权限！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        //图片回调处理
        mDownImageUtil.setImageCallBack(new ImageCallBack() {
            @Override
            public void onSuccess(String url) {
                Toast.makeText(ImageBigActivity.this, "图片保存成功：" + url, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed() {

            }
        });

        tv_more_comment_simple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_bottom_simple.setVisibility(View.GONE);
                ll_bottom.setVisibility(View.VISIBLE);
            }
        });
        iv_comment_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_bottom_simple.setVisibility(View.VISIBLE);
                ll_bottom.setVisibility(View.GONE);
            }
        });

        videoDisSendTv_simple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != imageDetail) {
                    picture_id = imageDetail.getAtlas_id() + "";
                }
                String comment = sendEt_simple.getText().toString();
                if (TextUtils.isEmpty(comment)) {
                    ToastUtil.showLongToast("请输入评论内容");
                    return;
                }

                PictureDataRequest.addPictureComment(picture_id, comment, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        sendEt_simple.setText("");
                        getCommentData();
                        ToastUtil.showLongToast("评论成功");
                    }
                });
            }
        });
        videoDisSendTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != imageDetail) {
                    picture_id = imageDetail.getAtlas_id() + "";
                }
                String comment = sendEt.getText().toString();
                if (TextUtils.isEmpty(comment)) {
                    ToastUtil.showLongToast("请输入评论内容");
                    return;
                }

                PictureDataRequest.addPictureComment(picture_id, comment, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        sendEt.setText("");
                        getCommentData();
                        ToastUtil.showLongToast("评论成功");
                    }
                });
            }
        });
    }

    @Override
    protected void initNet() {
        imageDetail = getIntent().getParcelableExtra("imageDetail");
        position = getIntent().getIntExtra("position", 0);

        //绑定适配器
        vp_viewpager.setAdapter(mPagerAdapter);
        vp_viewpager.setCurrentItem(position);

        ll_bottom_simple.setVisibility(View.VISIBLE);
        tv_pagenum_simple.setText(1 + position + "/" + imageDetail.getPictures_list().size());

        getCommentData();
        ll_bottom.setVisibility(View.GONE);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for (int i = 0; i < imageDetail.getPictures_list().size(); i++) {
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            iv.setLayoutParams(params);
            //封面
            Glide.with(this)
                    .load(imageDetail.getPictures_list().get(i).getImg_url())
                    .into(iv);
            pageview.add(iv);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        XPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    String picture_id;

    private void getCommentData() {
        //获取评列表
        if (null != imageDetail) {
            picture_id = imageDetail.getAtlas_id() + "";
        }
        //获取评列表
        PictureDataRequest.getPictureComment(picture_id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {
                                JSONArray dataJson = jsonObject.getJSONArray("data");
                                List<ImageDetailCommonBean> commonList = JsonUtil.json2List(dataJson.toString(), ImageDetailCommonBean.class);
                                ImageCommonAdapter adapter = new ImageCommonAdapter(ImageBigActivity.this);
                                adapter.setList(commonList);

//                                ImageDesAdapter adapter = new ImageDesAdapter(ImageDetailActivity.this);
//                                adapter.setList(commonList);
                                lv_comment.setAdapter(adapter);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    List<ImageView> pageview = new ArrayList<>();
    //数据适配器
    PagerAdapter mPagerAdapter = new PagerAdapter() {

        @Override
        //获取当前窗体界面数
        public int getCount() {
            // TODO Auto-generated method stub
            return imageDetail.getPictures_list().size();
        }

        @Override
        //断是否由对象生成界面
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        //是从ViewGroup中移出当前View
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(pageview.get(arg1));
        }

        //返回一个对象，这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(pageview.get(arg1));
            return pageview.get(arg1);
        }

    };


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        tv_pagenum_simple.setText(1 + position + "/" + imageDetail.getPictures_list().size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
